<template>
  <div class="container">
    <div class="container_page">
      <page-header :title="$t('points_addCard')"></page-header>
      <div class="bank_pay_popup">
        <div class="su_title">{{ $t('pay_enterBankCard') }}</div>
        <div class="stripe_card">
          <div id="payment-element"></div>
        </div>
        <div class="su_title bind_tip" v-if="showBindcard">
          <img
            :src="
              isBindCard
                ? require('@/assets/img/login/login_ic_check_selected.svg')
                : require('@/assets/img/login/login_ic_check_unselected.svg')
            "
            alt=""
            style="width: 15px;height: 15px; margin-right: 5px;"
            @click.prevent="isBindCard = !isBindCard"
          />
          <span @click.prevent="isBindCard = !isBindCard">{{
            $t('pay_addCardToWallet')
          }}</span>
        </div>        
      </div>

      <bottom-button
        :title="$t('wallet_addCard')"
        @click="createToken"
        background="var(--page-bg)"
      ></bottom-button>
      <!--加载脚本提示 -->
      <van-dialog v-model="isShowLoadError" :showConfirmButton="false">
        <div class="brief" style="padding-top: var(--gap);">
          {{ $t('error_netError') }}
        </div>
        <div class="btns">
          <div class="btn flex_center" @click="isShowLoadError = false">
            {{ $t('wallet_cancel') }}
          </div>
          <div class="btn flex_center" @click="refesh">
            {{ $t('home_confirm') }}
          </div>
        </div>
      </van-dialog>
    </div>
  </div>
</template>

<script>
import $api from '@/assets/js/api/index'
import { debounce } from '@/assets/js/util'
import { loadStripe } from '@stripe/stripe-js'
import share from '@/mixins/share'
export default {
  mixins: [share],
  data () {
    return {
      actionType: 'back', // back 绑定后返回原页面 rent 扫码页
      stripe: null,
      elements: null,
      isShowLoadError: false,
      isBinding: false,
      isBindCard: true,
      showBindcard: false,
      params: '',
      bankcardInfo: '',
      bankInfo: ''
    }
  },
  created () {
    this.getLang()
  },
  methods: {
    refesh () {
      window.location.reload()
    },
    //初始化
    async initialize () {
      try {
        this.$store.commit('startLoading')
        this.stripe = await loadStripe(this.$stripeKye, {
          locale: this.$i18n.locale.toLocaleLowerCase()
        }) //账号密匙key
        this.$store.commit('endLoading')
        this.elements = this.stripe.elements({})
        this.paymentElement = this.elements.create('card', {
          hidePostalCode: false,
          disableLink: true,
          style: {
            base: {
              color: '#39404D',
              fontWeight: '500',
              fontSize: '18px',
              fontSmoothing: 'antialiased',
              fontLineHeight: '18px',
              ':-webkit-autofill': {
                color: '#fce883'
              },
              '::placeholder': {
                color: '#AAAAAC'
              }
            }
          }
        })
        this.paymentElement.mount('#payment-element')
        this.$store.commit('endLoading')
      } catch (e) {
        this.$store.commit('endLoading')
        this.isShowLoadError = true
      }
    },
    createToken: debounce(async function () {
      try {
        if (this.isBinding) return
        this.isBinding = true
        this.$store.commit('startLoading')
        const { token, error } = await this.stripe.createToken(
          this.paymentElement
        ) //校验并获取卡信息
        this.closeLoading()
        if (error) {
          this.global.toast(error.message)
          return
        }

        this.bankcardInfo = {
          bankExpire: token.card.exp_month + '/' + token.card.exp_year, //卡日期
          bankName: token.card.brand, //银行名称
          bankNo: token.card.last4, //银行卡号
          bankType: token.card.funding, //卡的类型
          token: token.id, //卡token
          defaulted: 0,
          save: false,
          paymentChannel: 'stripe', // 支付渠道
          postalCode: token.card.address_zip, // 邮编
        }

        // 是否绑卡
        if (this.isBindCard) {
          this.bankcardInfo.save = true
          if (this.actionType == 'back') {
            const res = await $api.user.bindBankCard(this.bankcardInfo)
            if (res.code != '0') {
              this.global.toast(res.message, 10000)
              return
            }
          }
        }

        if (this.actionType == "back") {
          this.$router.replace("/wallet");
        } else {
          // this.$router.replace("/scan");
          this.$store.commit('startLoading')
          this.checkCredit()
        }
      } catch (e) {
        this.closeLoading()
      }
    }),
    closeLoading () {
      this.isBinding = false
      this.$store.commit('endLoading')
    },

    // 信用租借-前置检查
    checkCredit () {
      $api.home
        .creditRent({
          scanUrl: this.params.sno,
          source: 2,
          rentType: 1,
          scene: 1,
          paymentChannel: 'stripe',
          // bankcardId: this.isBindCard ? this.bankInfo.id : '',
          bankcardInfo: this.bankcardInfo
        })
        .then(res => {
          if (res.code == 0) {
            // localStorage.setItem('lastRentType', this.isBindCard ? '1' : '2')
            this.$router.push({
              path: '/rent/loading',
              query: {
                orderNo: res.data.order.orderNo,
                lastRentType: this.isBindCard ? '1' : '2'
              }
            })
          } else {
            this.global.toast(res.message)
          }
        })
    }    
  },
  mounted () {
    this.actionType = localStorage.getItem('actionType') || 'back'
    if (this.actionType == 'bindCardRent') {
      this.showBindcard = true
      this.isBindCard = false
    }
    this.params = localStorage.getItem('device_info')
      ? JSON.parse(localStorage.getItem('device_info'))
      : ''
    this.initialize()
  },
  computed: {}
}
</script>
<style scoped lang="scss">
.container_page {
  margin: 0;
  background-color: var(--page-bg);
  width: 100%;
  flex: 1;
  box-sizing: border-box;
}
.bank_pay_popup {
  padding: 0 var(--gap);
  min-height: 30vh;

  .stripe_card {
    background: #ececee;
    border-radius: 10px;
    padding: 16px 20px;
  }
  .title {
    text-align: center;
    font-weight: 600;
    color: #39404d;
    font-size: 18px;
    padding: 15px;
  }
  .su_title {
    font-weight: 600;
    color: #39404d;
    font-size: 14px;
    padding: 10px;
    color: #39404d;
  }
  .bind_tip {
    display: flex;
    align-items: center;
    margin-bottom: 100px;
  }
  .btn {
    margin-bottom: var(--gap);
  }
}
</style>
